/*
 * @Author: ydli
 * @LastEditTime: 2021-05-02 20:03:21
 * @Description: 
 */
import http from '../util/http';
import { createStore, Commit } from 'vuex';
export interface ResponseType<P> {
    code: number;
    msg: string;
    data: P;
}
export interface ColumnProps {
    _id: string;
    title: string;
    avatar?: ImageProps;
    description: string;
}
export interface ImageProps {
    _id?: string;
    url?: string;
    createdAt?: string;
    fitUrl?: string;
}
export interface PostProps {
    _id?: string;
    title: string;
    excerpt?: string;
    content?: string;
    image?: ImageProps | string;
    createdAt?: string;
    column: string;
    author?:string
}

export interface UserProps {
    isLogin: boolean;
    nickName?: string;
    _id?: string;
    column?: string;
    email?: string;
}

export interface GlobalErrorProps {
    status: boolean;
    message?: string;
}

export interface GlobalDataProps {
    token: string;
    columns: ColumnProps[];
    posts: PostProps[];
    user: UserProps;
    loading: boolean;
    error: GlobalErrorProps
}

// columns: testData,

const getAndCommit = async (url: string, mutationName: string, commit: Commit) => {
    const { data } = await http.get(url);
    commit(mutationName, data);
    return data;
}

const postAndCommit = async (url: string, mutationName: string, commit: Commit, payload: any) => {
    const { data } = await http.post(url, payload);
    commit(mutationName, data);
    return data;
}

const store = createStore<GlobalDataProps>({
    state: {
        error: { status: false },
        token: localStorage.getItem('token') || '',
        loading: false,
        columns: [],
        posts: [],
        user: { isLogin: false }
    },
    mutations: {
        // login(state) {
        //     state.user = { ...state.user, isLogin: true, name: 'ydlil', columnId: 1 }
        // },
        createPost(state, newPost) {
            state.posts.push(newPost);
        },
        fetchColumns(state, rawData) {
            state.columns = rawData.data.list;
        },
        fetchColumn(state, rawData) {
            state.columns = [rawData.data];
        },
        fetchPosts(state, rawData) {
            state.posts = rawData.data.list;
        },
        setLoading(state, status) {
            state.loading = status;
        },
        setError(state, e: GlobalErrorProps) {
            state.error = e;
        },
        fetchCurrentUser(state, rawData) {
            state.user = { isLogin: true, ...rawData.data }
            // localStorage.setItem('user',JSON.stringify(state.user));
        },
        login(state, rawData) {
            console.log('00000');
            const { token } = rawData.data
            state.token = token;
            localStorage.setItem('token', token);
            http.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        },
        logout(state) {
            state.token = '';
            localStorage.removeItem('token');
            delete http.defaults.headers.common['Authorization'];
        }
    },
    actions: {
        fetchColumns({ commit }) {
            return getAndCommit('/columns', 'fetchColumns', commit);
        },
        fetchColumn({ commit }, cid) {
            return getAndCommit(`/columns/${cid}`, 'fetchColumn', commit);
        },
        fetchPosts({ commit }, cid) {
            return getAndCommit(`/columns/${cid}/posts`, 'fetchPosts', commit);
        },
        fetchCurrentUser({ commit }) {
            return getAndCommit('/user/current', 'fetchCurrentUser', commit);
        },
        login({ commit }, payload) {
            return postAndCommit('/user/login', 'login', commit, payload);
        },
        createPost({ commit }, payload) {
            return postAndCommit('/posts', 'createPost', commit, payload);
        },
        // 组合action
        loginAndFetch({ dispatch }, loginData) {
            return dispatch('login', loginData).then(() => {
                return dispatch('fetchCurrentUser');
            })
        }
    },
    getters: {
        getColumnById: (state) => (id: string) => {
            return state.columns.find(c => c._id === id);
        },
        getPostsByCid: (state) => (cid: string) => {
            return state.posts.filter(post => post.column === cid);
        },
        getCurrentPost:(state) => (id:string) =>{
            return state.posts.find(post => post._id === id);
        }
    }
});

export default store;